package com.xbongbong.pro.statistics.configs;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.xbongbong.config.DataSourceNames;
import com.xbongbong.config.DynamicDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 配置放在各自的启动项目里，避免无用的配置增加
 * @Author 梁鲁江
 * 创建时间 2021/10/13 15:02
 * 修改时间  2021/10/13 15:02
 */
@Configuration
public class DynamicDataSourceConfig {
    protected Logger logger = LoggerFactory.getLogger(getClass());
    /**
     * 创建 com.xbongbong.config.DataSource Bean
     * */
    
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.druid.mysql-data")
    public DataSource oneDataSource(){
        DataSource dataSource = DruidDataSourceBuilder.create().build();
        return dataSource;
    }
 
/*    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.druid.ck-data")
    public DataSource twoDataSource(){
        DataSource dataSource = DruidDataSourceBuilder.create().build();
        return dataSource;
    }*/
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.druid.star-data")
    public DataSource twoDataSource(){
        DataSource dataSource = DruidDataSourceBuilder.create().build();
        return dataSource;
    }
    
    /**
     * 如果还有数据源,在这继续添加 com.xbongbong.config.DataSource Bean
     * */
    
    @Bean
    @Primary
    public DynamicDataSource dataSource(DataSource oneDataSource, DataSource twoDataSource) {
        Map<Object, Object> targetDataSources = new HashMap<>(2);
        targetDataSources.put(DataSourceNames.MYSQL_DATA, oneDataSource);
        targetDataSources.put(DataSourceNames.STAR_DATA, twoDataSource);
//        targetDataSources.put(DataSourceNames.STAR_DATA, thirdDataSource);
        // 还有数据源,在targetDataSources中继续添加
//        logger.info("===DataSources:" + targetDataSources);
        return new DynamicDataSource(oneDataSource, targetDataSources);
    }
}
